package com.example.oom;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtNewMethod;

import java.util.ArrayList;
import java.util.List;

public class CompressedClassSpaceOOM {
    public static void main(String[] args) {
        System.out.println("开始模拟 Compressed class space OOM...");

        List<Class<?>> classes = new ArrayList<>();
        ClassPool pool = ClassPool.getDefault();
        int count = 0;

        try {
            while (true) {
                CtClass ctClass = pool.makeClass("demo.GeneratedClass" + count);
                // 添加一个简单方法，避免优化
                ctClass.addMethod(CtNewMethod.make(
                        "public void m" + count + "() { System.out.println(" + count + "); }",
                        ctClass
                ));
                // 加载类
                Class<?> clazz = ctClass.toClass();
                classes.add(clazz);

                count++;
                if (count % 1000 == 0) {
                    System.out.println("已加载类数量: " + count);
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("触发 Compressed class space OOM，已加载类: " + count);
        }
    }
}
